#include "pwext.hpp"
#include <list>

class data;

// [[ex03cj]]
// DEBUG descr A barrier implementation attempt using a semaphore and an event.
class barrier 
{
public:
	barrier(int count) :
		flip_(0), count_(count)
	{ }

	// May be called only by the control thread, to
	// adjust the number of workers
	int add_workers(int add)
	{
		count_ += add; // add may be negative
		return count_;
	}

	// Workers call this method to synchronize on the
	// barrier
	void sync()
	{
		flip_.signal(1);
		flop_.wait();
	}

	// Control calls this method to wait for the barrier
	// to be reached by all the workers
	void wait()
	{
		flip_.wait(count_);
	}

	// Control calls this method to release the workers
	// from the barrier
	void signal()
	{
		flop_.pulse();
	}

protected:
	// control waits for workers
	pw::semaphore flip_; 
	// workers wait for control
	pw::event flop_; 
	// number of worker threads synchronized by the
	// barrier
	int count_; 
};
// END
